//index.js
//获取应用实例
// 引入SDK核心类
var QQMapWX = require('../../libs/qqmap-wx-jssdk.min.js')
var Promise = require('../../libs/es6-promise.min.js')
var id = 1;
var qqmapsdk, that, mapCtx, marker = {
    id: id += 1,
    latitude: 0,
    longitude: 0,
    width: 36,
    height: 36,
    iconPath: '../../image/start.png'
  },
  key = '26KBZ-3XELO-YNWWI-SFMI5-JIDX5-2AFWO'
const app = getApp()

/**
 * 弹出菜单选择poi
 */
function choose_pois() {
  return new Promise(function(resolve, reject) {
    wx.showActionSheet({
      itemList: that.data.pois,
      success: function(res) {
        resolve(res.tapIndex)
      },
      fail: function(res) {
        reject(res.errMsg)
      }
    })
  })
}

/**
 * 绘制起点到终点的路径
 */
function draw_route(lat, lng) {
  return new Promise(function(resolve, reject) {
    wx.request({
      url: 'https://apis.map.qq.com/ws/direction/v1/bicycling/?from=' + lat + '&to=' + lng + '&key=' + key + '',
      success(res) {
        if (res.statusCode == 200) {
          if (res.data.status == 0) {

            //polyline坐标解压
            var ply = res.data.result.routes[0].polyline
            for (var i = 2; i < ply.length; i++) {
              ply[i] = ply[i - 2] + ply[i] / 1000000
            }

            var polylines = [];
            var p = {
                points: [],
                color: '#FF0000DD',
                width: 4,
                arrowLine: true,
                // dottedLine: true
              },
              ps = {
                points: [],
                padding: [0]
              };

            while (ply.length / 2 > 0) {
              var lat = ply.pop(),
                lng = ply.pop()

              var i = {
                longitude: lat,
                latitude: lng
              }
              p.points.push(i)
              ps.points.push(i)
            }

            polylines.push(p)
            that.setData({
              polyline: polylines,
              latitude: that.data.end.latitude,
              longitude: that.data.end.longitude
            })

            mapCtx.includePoints(ps)
            resolve()

          } else
            reject()
        } else reject()
      },
      fail(err) {
        reject(err)
      }
    })
  })

}

/**
 * 获取当前位置地址
 */
function my_address(lat, lng) {
  return new Promise(function(resolve, reject) {
    // 调用接口
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: lat ? lat : that.data.latitude,
        longitude: lng ? lng : that.data.longitude
      },
      get_poi: 1,
      success: function(res) {
        var result = res.result;
        if (res.status == 0) {
          resolve(result)
        } else reject(res)
      },
      fail(err) {
        reject(err)
      }
    })

  });

}

/**
 * 定位到当前位置
 */
function my_location() {
  return new Promise(function(resolve, reject) {
    wx.getLocation({
      type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
      success: function(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        })
        resolve(res)
      },
      fail(err) {
        reject(err)
      }
    })
  })
}

Page({
  data: {
    latitude: 0, //当前纬度
    longitude: 0, //当前经度

    start: {
      start: '你在哪儿,拖动地图标记上车点', //上车点(地址)
      address: '',
      latitude: 0,
      longitude: 0
    },
    end: {
      end: '要去哪儿,看看有没有顺路的', //下车点(地址)
      address: '',
      latitude: 0,
      longitude: 0
    },

    pois: [],
    pois_list: [],
    polyline: [],
    whiching: 'start', //当前正在选择起点还是终点,默认起点
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  tap_: function(event) {

    var dir = event.currentTarget.dataset.dir
    that.setData({
      whiching: dir
    })

    mapCtx.getCenterLocation({
      success: function(res) {
        my_address(res.latitude, res.longitude).then(function(result) {
          var list = []
          result.pois.slice(0, 6).map(function(m) {
            list.push({
              title: m.title,
              address: m.address,
              lat: m.location.lat,
              lng: m.location.lng
            })
          })
          that.setData({
            pois: list.map(m => m.title),
            pois_list: list
          })

          choose_pois().then(function(res) {

            var m = marker,
              mks = that.data.markers

            if (dir == 'start') {

              m.latitude = that.data.pois_list[res].lat
              m.longitude = that.data.pois_list[res].lng

              if (mks.length == 1)
                mks.push(m)
              else mks[0] = m

              that.setData({
                start: {
                  start: that.data.pois[res],
                  address: that.data.pois_list[res].address,
                  latitude: that.data.pois_list[res].lat,
                  longitude: that.data.pois_list[res].lng
                },
                markers: mks
              })
              
            } else if (dir == 'end') {

              m.latitude = that.data.pois_list[res].lat
              m.longitude = that.data.pois_list[res].lng
              m.iconPath = '../../image/flag-o.png'

              if (mks.length == 1)
                mks.push(m)
              else mks[1] = m

              that.setData({
                end: {
                  end: that.data.pois[res],
                  address: that.data.pois_list[res].address,
                  latitude: that.data.pois_list[res].lat,
                  longitude: that.data.pois_list[res].lng
                },
                markers: mks
              })
            }

            //获得起点与终点并绘制路径
            if (that.data.start.latitude != 0 && that.data.end.end.longitude != 0) {
              var lat = that.data.start.latitude + ',' + that.data.start.longitude,
                lng = that.data.end.latitude + ',' + that.data.end.longitude

              draw_route(lat, lng).then(function() {

                // var m1 = marker
                // m1.latitude = poly[0].points[0].latitude
                // m1.longitude = poly[0].points[0].longitude

                // var mks = that.data.markers
                // if (mks.length == 1)
                //   mks.push(m1)
                // else mks[0] = m1

                // that.setData({
                //   markers: mks
                // })




                // if (that.data.whiching == 'end') {



                //   ///TODO: 下叙逻辑使用watch end做监视，只要end有变更，则更新marker
                //   //绘制终点marker
                //   var m = marker
                //   m.iconPath = '../../image/flag-o.png'
                //   m.latitude = that.data.pois_list[res].lat
                //   m.longitude = that.data.pois_list[res].lng

                //   var mks = that.data.markers
                //   if (mks.length == 1)
                //     mks.push(m)
                //   else mks[1] = m

                //   that.setData({
                //     markers: mks
                //   })

                //   wx.showToast({
                //     title: '捎人或者求捎',
                //   })
                // }

              })
            }

          }, function(err) {
            console.error(err)
          })

        })
      }
    })

  },
  locate() { //定位到当前位置
    my_location()
  },
  regionchange(e) { //地图改变位置调用方法
  },
  markertap(e) { //点击地图标记触发
    console.log(e.markerId)
  },
  tap(event) {
    console.log(event)
  },
  onReady: function() {
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: key
    });
    mapCtx = wx.createMapContext('myMap')
  },
  onLoad: function() {
    that = this

    // 获取地理位置
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userLocation']) {
          if (res) {
            my_location().then(
              function(res) {
                my_address().then((result) => {

                  var m = marker;
                  m.latitude = result.location.lat
                  m.longitude = result.location.lng

                  that.setData({
                    start: {
                      start: result.formatted_addresses.recommend,
                      address: result.address,
                      latitude: result.location.lat,
                      longitude: result.location.lng
                    },
                    markers: [m],
                  })

                }, (error) => {
                  console.warn(error)
                })
              }
            )
          }
        } else {
          //授权获取地理位置
          wx.authorize({
            scope: 'scope.userLocation',
          })
        }
      }
    })
  },
})